<template>
  <page-dialog
    :title="dialogInfo.title"
    v-model:visible="shows"
    :width="dialogInfo.width"
    :bt-loading="dialogInfo.btLoading"
    :bt-list="dialogInfo.btList"
  >
    <!-- 条件栏 -->
    <new-page-filter
      v-model:query="filterInfo.query"
      :filter-list="filterInfo.list"
    >
      <template v-slot:filter-button>
        <div class="flex_wrap_between_middle">
          <div style="display: flex; width: 50%">
            <p style="margin-right: 20px; max-width: 50%" class="text-style">
              产品名称: {{ info.commonName }}
            </p>
            <p class="text-style">生产批号: {{ info.batchNumber }}</p>
          </div>
          <div style="display: flex; width: 50%; justify-content: flex-end">
            <el-input
              v-model="filterInfo.keyword"
              :clearable="true"
              placeholder="请输入个体码"
              style="margin-right: 10px; width: 217px"
              @keyup.enter.native="search"
              @input="(e) => (filterInfo.keyword = validSe(e))"
            />
            <el-button @click="search">搜索</el-button>
          </div>
        </div>
      </template>
    </new-page-filter>
    <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
      <dialog-table
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        ref="depotTable"
        :api="tableInfo.api"
        v-model:data="tableInfo.data"
        :check-box="false"
        :tab-index="true"
        :listen-height="false"
        :handle="tableInfo.handle"
        :pager="false"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        @handleEvent="handleEvent"
      >
      </dialog-table>
    </el-form>
    <page-dialog
      :title="revokeDialogInfo.title"
      v-model:visible="revokeDialogInfo.revokeVisible"
      :width="revokeDialogInfo.width"
      :bt-loading="revokeDialogInfo.btLoading"
      :bt-list="revokeDialogInfo.btList"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        :data="formInfo.data"
        :field-list="formInfo.fieldList"
        :rules="formInfo.rules"
        :label-width="formInfo.labelWidth"
        style="width: 100%"
      >
        <template v-slot:form-invalidQty>
          <div
            v-if="formInfo.data.codeType === 1 || formInfo.data.codeType === 4"
          >
            <el-input-number
              v-model.lazy="formInfo.data.largeUnitQty"
              clearable
              style="width: 100%"
              controls-position="right"
              :precision="
                formInfo.data.qtyOperateMode === 0 ||
                formInfo.data.qtyOperateMode === 2
                  ? 0
                  : systemConfig.qty_show_precision
              "
              @change="
                changeLarge($event, formInfo.data, formInfo.data.largeUnitQty)
              "
              :min="0"
              :max="largeMax(formInfo.data)"
            />
            <span style="padding-left: 10px; position: absolute">{{
              formInfo.data.unitName
            }}</span>

            <div
              v-if="
                formInfo.data.unitConvertCoefficient > 1 &&
                formInfo.data.qtyOperateMode === 2
              "
            >
              <el-input-number
                style="width: 100%; margintop: 18px"
                v-model.lazy="formInfo.data.smallUnitQty"
                clearable
                controls-position="right"
                :precision="0"
                :min="0"
                :max="smallMax(formInfo.data)"
              />
              <span style="padding-left: 10px; position: absolute">{{
                formInfo.data.calcUnitName
              }}</span>
            </div>
          </div>
          <span
            v-else-if="
              formInfo.data.codeType === 2 || formInfo.data.codeType === 3
            "
            >{{ $fn.qtyFormatter(formInfo.data.qty) }}</span
          >
        </template>
      </page-form>
    </page-dialog>
  </page-dialog>
</template>

<script setup name="IndividualDetails">
import {
  consumesCancel,
  getConsumeOrderDetailCustomizeListAll,
  revokeConsumeOrderDetail,
} from '@/api/stock.js'
import { getCustomizeSetting } from '@/api/customize'
import utils from '@/common/js/utils'

const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps({
  api: {
    type: Function,
    default: getConsumeOrderDetailCustomizeListAll,
  },
  showDialog: {
    type: Boolean,
  },
  info: {
    type: Object,
    default: function () {
      return {}
    },
  },
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  withSurgery: {
    type: Boolean,
    default: function () {
      return false
    },
  },
  consumeSourceId: {
    type: Number,
    default: -2,
  },
  sourceType: {
    type: Number,
  },
})

const formInfo = ref({
  data: {},
  fieldList: [{ label: '数量', value: 'invalidQty', type: 'slot' }],
  labelWidth: '180px',
})
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
// 过滤相关配置
const filterInfo = ref({
  keyword: '',
  query: {
    queryMap: {
      ...props.query,
    },
    queryParams: {},
    customizeUserVO: {},
  },
  list: [{ slot: true, value: 'button' }],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  copyData: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '撤回',
        event: showRevokable,
        show: proxy.$permission('consumeOrder:revokable'),
        ifRender: ifRenderRevokable,
      },
      {
        label: '无痕撤回',
        event: showRevokeDialog,
        show: proxy.$permission('consumeOrder:revoke'),
        ifRender: ifRenderValue,
      },
    ],
  },
})
// 弹窗相关
const dialogInfo = ref({
  title: '个体详情',
  width: '90%',
  btLoading: false,
  btList: [{ label: '关闭', event: handleClose, show: true }],
})
//消耗数量弹窗
const revokeDialogInfo = ref({
  title: '撤回',
  width: '30%',
  revokeVisible: false,
  btLoading: false,
  btList: [
    { label: '关闭', event: revokeHandleClose, show: true },
    { label: '确定', event: revoke, show: true },
  ],
})
const selectRow = ref('')
const isRefresh = ref(false)

const shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emits('update:showDialog', newValue) // 更新父组件visible
  },
})

setData()
function setData() {
  let obj = {
    price: {
      label: '单价',
      value: 'price',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('consumeOrder:price'),
      show: false,
      hidden: true,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('consumeOrder:price'),
      show: false,
      hidden: true,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      permission: !proxy.$permission('consumeOrder:price'),
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
    invalidQty: {
      label: '撤回数量',
      value: 'invalidQty',
      type: 'column',
      componentType: 'number',
      formatter: utils.qtyFormatter,
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
}
function ifRenderValue(row) {
  return row.canInvalidCalcQty > 0 && props.consumeSourceId === -2
}
function ifRenderRevokable(row) {
  return (
    row.canInvalidCalcQty > 0 &&
    props.consumeSourceId === -2 &&
    props.sourceType !== '79'
  )
}
//撤回
function showRevokeDialog(row) {
  formInfo.value.data = row
  revokeDialogInfo.value.revokeVisible = true
}
//撤回弹窗关闭
function revokeHandleClose() {
  //清空数据
  formInfo.value.data = {}
  revokeDialogInfo.value.revokeVisible = false
  // handleClose();
}
function showRevokable(row) {
  //撤回
  props.api(filterInfo.value.query).then((res) => {
    if (res && res.success) {
      let data = res.data
      let item = data.find((item) => item.id === row.id)
      if (item.canInvalidCalcQty > 0) {
        shows.value = false
        emits('showRevokable', row.id)
      } else {
        proxy.$message({
          message: '无可撤回数量，请刷新数据',
          type: 'warning',
          duration: 3500,
          showClose: true,
        })
        return
      }
    }
  })
}
function revoke() {
  let smallUnitQty = parseFloat(formInfo.value.data.smallUnitQty || 0)
  let unitConvertCoefficient = parseFloat(
    formInfo.value.data.unitConvertCoefficient || 1
  )
  let largeUnitQty = parseFloat(formInfo.value.data.largeUnitQty || 0)
  let invalidCalcQty = proxy.$fn.accAdd(
    proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
    smallUnitQty
  )
  let invalidQty = proxy.$fn.accDiv(invalidCalcQty, unitConvertCoefficient)
  formInfo.value.data.invalidCalcQty = invalidCalcQty
  formInfo.value.data.invalidQty = proxy.$fn.qtyFormatter(invalidQty)
  formInfo.value.data.invalidSumAmount = proxy.$fn.priceFormatter(
    proxy.$fn.accDiv(
      proxy.$fn.accMul(invalidCalcQty, parseFloat(formInfo.value.data.price)),
      unitConvertCoefficient
    )
  )
  revokeConsumeOrderDetail(formInfo.value.data).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = {}
      revokeDialogInfo.value.revokeVisible = false
      getList()
    }
  })
}
function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    return parseInt(row.calcQty / row.unitConvertCoefficient)
  } else {
    return row.qty
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(row.calcQty / row.unitConvertCoefficient)
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.calcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  let largeUnitQty = parseInt(row.calcQty / row.unitConvertCoefficient)
  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (largeUnitQty > 0 && e === largeUnitQty) {
      let smallUnitQty = parseInt(row.calcQty % row.unitConvertCoefficient)
      if (row.smallUnitQty > smallUnitQty) {
        row.smallUnitQty = smallUnitQty
      }
    }
  }
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
function search() {
  const search = filterInfo.value.keyword
  if (search) {
    tableInfo.value.data = tableInfo.value.copyData.filter((data) => {
      return Object.keys(data).some((key) => {
        if (key === 'qrCode') {
          return String(data[key]).indexOf(search) > -1
        } else if (key === 'uniqueCode') {
          return String(data[key]).indexOf(search) > -1
        } else if (key === 'factorySubCode') {
          return String(data[key]).indexOf(search) > -1
        } else if (key === 'factoryMainCode') {
          return String(data[key]).indexOf(search) > -1
        }
      })
    })
  } else {
    tableInfo.value.data = tableInfo.value.copyData
  }
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  emits('reset', isRefresh.value)
}
function handleEvent(event, data) {
  switch (event) {
    case 'list':
      tableInfo.value.copyData = data
      if (!data.length > 0) {
        handleClose()
      }
      break
  }
}
function returnUse(row) {
  consumesCancel(row.id).then((resp) => {
    if (resp && resp.success) {
      isRefresh.value = true
      getList()
    }
  })
}
function getCustomize() {
  let _tableInfo = tableInfo.value
  let param = {
    tableKey:
      'consumeIndividualDetails-com.slip.spd.entity.vo.stock.ConsumeOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = res.data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )
      _tableInfo.api = props.api
      getList()
    }
  })
}
</script>

<style scoped lang="scss">
:deep(.filter-item) {
  width: 100%;
}
.text-style {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
